<!DOCTYPE html>



  


<html class="theme-next gemini use-motion" lang="zh-CN">
<head>
  <meta charset="UTF-8"/>
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=2"/>
<meta name="theme-color" content="#222">












<meta http-equiv="Cache-Control" content="no-transform" />
<meta http-equiv="Cache-Control" content="no-siteapp" />






















<link href="/lib/font-awesome/css/font-awesome.min.css?v=4.6.2" rel="stylesheet" type="text/css" />

<link href="/css/main.css?v=6.1.0" rel="stylesheet" type="text/css" />


  <link rel="apple-touch-icon" sizes="180x180" href="/images/apple-touch-icon-next.png?v=6.1.0">


  <link rel="icon" type="image/png" sizes="32x32" href="/images/favicon-32x32-next.png?v=6.1.0">


  <link rel="icon" type="image/png" sizes="16x16" href="/images/favicon-16x16-next.png?v=6.1.0">


  <link rel="mask-icon" href="/images/logo.svg?v=6.1.0" color="#222">









<script type="text/javascript" id="hexo.configurations">
  var NexT = window.NexT || {};
  var CONFIG = {
    root: '/',
    scheme: 'Gemini',
    version: '6.1.0',
    sidebar: {"position":"left","display":"post","offset":12,"b2t":false,"scrollpercent":false,"onmobile":false},
    fancybox: false,
    fastclick: false,
    lazyload: false,
    tabs: true,
    motion: {"enable":true,"async":false,"transition":{"post_block":"fadeIn","post_header":"slideDownIn","post_body":"slideDownIn","coll_header":"slideLeftIn","sidebar":"slideUpIn"}},
    algolia: {
      applicationID: '',
      apiKey: '',
      indexName: '',
      hits: {"per_page":10},
      labels: {"input_placeholder":"Search for Posts","hits_empty":"We didn't find any results for the search: ${query}","hits_stats":"${hits} results found in ${time} ms"}
    }
  };
</script>


  




  <meta name="description" content="Hystrix是什么？在分布式系统中，每个服务都可能会调用很多其他服务，被调用的那些服务就是依赖服务，有的时候某些依赖服务出现故障也是很正常的。 Hystrix可以让我们在分布式系统中对服务间的调用进行控制，加入一些调用延迟或者依赖故障的容错机制。">
<meta name="keywords" content="spring-cloud,hystrix">
<meta property="og:type" content="article">
<meta property="og:title" content="Hystrix介绍和简单使用">
<meta property="og:url" content="http://www.saily.top/2018/03/11/hystrix01/index.html">
<meta property="og:site_name" content="帆的博客">
<meta property="og:description" content="Hystrix是什么？在分布式系统中，每个服务都可能会调用很多其他服务，被调用的那些服务就是依赖服务，有的时候某些依赖服务出现故障也是很正常的。 Hystrix可以让我们在分布式系统中对服务间的调用进行控制，加入一些调用延迟或者依赖故障的容错机制。">
<meta property="og:locale" content="zh-CN">
<meta property="og:image" content="http://www.saily.top/img/hystrix/什么是分布式系统以及其中的故障和hystrix.png">
<meta property="og:image" content="http://www.saily.top/img/hystrix/依赖服务的故障导致服务被拖垮以及故障的蔓延.png">
<meta property="og:image" content="http://www.saily.top/img/hystrix/资源隔离如何保护依赖服务的故障不要拖垮整个系统.png">
<meta property="og:image" content="http://www.saily.top/img/hystrix/商品服务接口导致缓存服务资源耗尽的问题.png">
<meta property="og:image" content="http://www.saily.top/img/hystrix/信号量的资源隔离与限流的说明.png">
<meta property="og:image" content="http://www.saily.top/img/hystrix/线程池隔离和信号量隔离的原理以及区别.png">
<meta property="og:updated_time" content="2018-06-10T10:05:10.363Z">
<meta name="twitter:card" content="summary">
<meta name="twitter:title" content="Hystrix介绍和简单使用">
<meta name="twitter:description" content="Hystrix是什么？在分布式系统中，每个服务都可能会调用很多其他服务，被调用的那些服务就是依赖服务，有的时候某些依赖服务出现故障也是很正常的。 Hystrix可以让我们在分布式系统中对服务间的调用进行控制，加入一些调用延迟或者依赖故障的容错机制。">
<meta name="twitter:image" content="http://www.saily.top/img/hystrix/什么是分布式系统以及其中的故障和hystrix.png">



  <link rel="alternate" href="/atom.xml" title="帆的博客" type="application/atom+xml" />




  <link rel="canonical" href="http://www.saily.top/2018/03/11/hystrix01/"/>



<script type="text/javascript" id="page.configurations">
  CONFIG.page = {
    sidebar: "",
  };
</script>

  <title>Hystrix介绍和简单使用 | 帆的博客</title>
  









  <noscript>
  <style type="text/css">
    .use-motion .motion-element,
    .use-motion .brand,
    .use-motion .menu-item,
    .sidebar-inner,
    .use-motion .post-block,
    .use-motion .pagination,
    .use-motion .comments,
    .use-motion .post-header,
    .use-motion .post-body,
    .use-motion .collection-title { opacity: initial; }

    .use-motion .logo,
    .use-motion .site-title,
    .use-motion .site-subtitle {
      opacity: initial;
      top: initial;
    }

    .use-motion {
      .logo-line-before i { left: initial; }
      .logo-line-after i { right: initial; }
    }
  </style>
</noscript>

</head>

<body itemscope itemtype="http://schema.org/WebPage" lang="zh-CN">

  
  
    
  

  <div class="container sidebar-position-left page-post-detail">
    <div class="headband"></div>

    <header id="header" class="header" itemscope itemtype="http://schema.org/WPHeader">
      <div class="header-inner"><div class="site-brand-wrapper">
  <div class="site-meta ">
    

    <div class="custom-logo-site-title">
      <a href="/" class="brand" rel="start">
        <span class="logo-line-before"><i></i></span>
        <span class="site-title">帆的博客</span>
        <span class="logo-line-after"><i></i></span>
      </a>
    </div>
      
        <p class="site-subtitle">扬帆起航</p>
      
  </div>

  <div class="site-nav-toggle">
    <button aria-label="切换导航栏">
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
    </button>
  </div>
</div>




<nav class="site-nav">
  
    <ul id="menu" class="menu">
      
        
        
        
          
          <li class="menu-item menu-item-home">
    <a href="/" rel="section">
      <i class="menu-item-icon fa fa-fw fa-home"></i> <br />首页</a>
  </li>
        
        
        
          
          <li class="menu-item menu-item-about">
    <a href="/about/" rel="section">
      <i class="menu-item-icon fa fa-fw fa-user"></i> <br />关于</a>
  </li>
        
        
        
          
          <li class="menu-item menu-item-tags">
    <a href="/tags/" rel="section">
      <i class="menu-item-icon fa fa-fw fa-tags"></i> <br />标签</a>
  </li>
        
        
        
          
          <li class="menu-item menu-item-categories">
    <a href="/categories/" rel="section">
      <i class="menu-item-icon fa fa-fw fa-th"></i> <br />分类</a>
  </li>
        
        
        
          
          <li class="menu-item menu-item-archives">
    <a href="/archives/" rel="section">
      <i class="menu-item-icon fa fa-fw fa-archive"></i> <br />归档</a>
  </li>

      
      
        <li class="menu-item menu-item-search">
          
            <a href="javascript:;" class="popup-trigger">
          
            
              <i class="menu-item-icon fa fa-search fa-fw"></i> <br />搜索</a>
        </li>
      
    </ul>
  

  

  
    <div class="site-search">
      
  <div class="popup search-popup local-search-popup">
  <div class="local-search-header clearfix">
    <span class="search-icon">
      <i class="fa fa-search"></i>
    </span>
    <span class="popup-btn-close">
      <i class="fa fa-times-circle"></i>
    </span>
    <div class="local-search-input-wrapper">
      <input autocomplete="off"
             placeholder="搜索..." spellcheck="false"
             type="text" id="local-search-input">
    </div>
  </div>
  <div id="local-search-result"></div>
</div>



    </div>
  
</nav>



  



</div>
    </header>

    


    <main id="main" class="main">
      <div class="main-inner">
        <div class="content-wrap">
          
            

          
          <div id="content" class="content">
            

  <div id="posts" class="posts-expand">
    

  

  
  
  

  

  <article class="post post-type-normal" itemscope itemtype="http://schema.org/Article">
  
  
  
  <div class="post-block">
    <link itemprop="mainEntityOfPage" href="http://www.saily.top/2018/03/11/hystrix01/">

    <span hidden itemprop="author" itemscope itemtype="http://schema.org/Person">
      <meta itemprop="name" content="杨帆">
      <meta itemprop="description" content="">
      <meta itemprop="image" content="/img/photo/bug.png">
    </span>

    <span hidden itemprop="publisher" itemscope itemtype="http://schema.org/Organization">
      <meta itemprop="name" content="帆的博客">
    </span>

    
      <header class="post-header">

        
        
          <h1 class="post-title" itemprop="name headline">Hystrix介绍和简单使用
              
            
          </h1>
        

        <div class="post-meta">
          <span class="post-time">
            
                
            

            
              <span class="post-meta-item-icon">
                <i class="fa fa-calendar-o"></i>
              </span>
              
                <span class="post-meta-item-text">发表于</span>
              
              <time title="创建于" itemprop="dateCreated datePublished" datetime="2018-03-11T12:05:39+08:00">3月 11 2018</time>
            

            
            

            
          </span>

          
            <span class="post-category" >
            
              <span class="post-meta-divider">|</span>
            
              <span class="post-meta-item-icon">
                <i class="fa fa-folder-o"></i>
              </span>
              
                <span class="post-meta-item-text">分类于</span>
              
              
                <span itemprop="about" itemscope itemtype="http://schema.org/Thing"><a href="/categories/hystrix/" itemprop="url" rel="index"><span itemprop="name">hystrix</span></a></span>

                
                
              
            </span>
          

          
            
          

          
          

          
            <span class="post-meta-divider">|</span>
            <span class="post-meta-item-icon"
            >
            <i class="fa fa-eye"></i>
             阅读次数： 
            <span class="busuanzi-value" id="busuanzi_value_page_pv" ></span>
            </span>
          

          

          

        </div>
      </header>
    

    
    
    
    <div class="post-body" itemprop="articleBody">

      
      

      
        <h1 id="Hystrix是什么？"><a href="#Hystrix是什么？" class="headerlink" title="Hystrix是什么？"></a>Hystrix是什么？</h1><p>在分布式系统中，每个服务都可能会调用很多其他服务，被调用的那些服务就是依赖服务，有的时候某些依赖服务出现故障也是很正常的。</p>
<p>Hystrix可以让我们在分布式系统中对服务间的调用进行控制，加入一些调用延迟或者依赖故障的容错机制。</p>
<a id="more"></a>
<p>Hystrix通过将依赖服务进行资源隔离，进而组织某个依赖服务出现故障的时候，这种故障在整个系统所有的依赖服务调用中进行蔓延，同时Hystrix还提供故障时的fallback降级机制</p>
<p>总而言之，Hystrix通过这些方法帮助我们提升分布式系统的可用性和稳定性。</p>
<p><img src="/img/hystrix/什么是分布式系统以及其中的故障和hystrix.png" alt="什么是分布式系统以及其中的故障和hystrix"></p>
<h1 id="Hystrix的历史"><a href="#Hystrix的历史" class="headerlink" title="Hystrix的历史"></a>Hystrix的历史</h1><p>hystrix就是一种高可用保障的一个框架，预先封装好的为了解决某个特定领域的特定问题的一套代码库。用了框架之后，来解决这个领域的特定的问题，就可以大大减少我们的工作量，提升我们的工作质量和工作效率。</p>
<p>Netflix（可以认为是国外的优酷或者爱奇艺之类的视频网站），API团队从2011年开始做一些提升系统可用性和稳定性的工作，Hystrix就是从那时候开始发展出来的。</p>
<p>在2012年的时候，Hystrix就变得比较成熟和稳定了，Netflix中，除了API团队以外，很多其他的团队都开始使用Hystrix。</p>
<p>时至今日，Netflix中每天都有数十亿次的服务间调用，通过Hystrix框架在进行，而Hystrix也帮助Netflix网站提升了整体的可用性和稳定性</p>
<h1 id="Hystrix的设计原则"><a href="#Hystrix的设计原则" class="headerlink" title="Hystrix的设计原则"></a>Hystrix的设计原则</h1><p>hystrix为了实现高可用性的架构，它的设计原则:</p>
<ol>
<li>对依赖服务调用时出现的调用延迟和调用失败进行控制和容错保护</li>
<li>在复杂的分布式系统中，阻止某一个依赖服务的故障在整个系统中蔓延，服务A-&gt;服务B-&gt;服务C，服务C故障了，服务B也故障了，服务A故障了，整套分布式系统全部故障，整体宕机</li>
<li>提供fail-fast（快速失败）和快速恢复的支持</li>
<li>提供fallback优雅降级的支持</li>
<li>支持近实时的监控、报警以及运维操作</li>
</ol>
<h1 id="Hystrix要解决的问题"><a href="#Hystrix要解决的问题" class="headerlink" title="Hystrix要解决的问题"></a>Hystrix要解决的问题</h1><p>在复杂的分布式系统架构中，每个服务都有很多的依赖服务，而每个依赖服务都可能会故障。如果服务没有和自己的依赖服务进行隔离，那么可能某一个依赖服务的故障就会拖垮当前这个服务。</p>
<p>举例来说，某个服务有30个依赖服务，每个依赖服务的可用性非常高，已经达到了99.99%的高可用性，那么该服务的可用性就是99.99%的30次方，也就是99.7%的可用性，99.7%的可用性就意味着0.3%的请求可能会失败，因为0.3%的时间内系统可能出现了故障导致系统不可用。对于1亿次访问来说，0.3%的请求失败，也就意味着30万次请求会失败，也意味着每个月有2个小时的时间系统是不可用的。</p>
<p>在真实生产环境中，可能更加糟糕，也就是说，即使你每个依赖服务都是99.99%高可用性，但是一旦你有几十个依赖服务，还是会导致你每个月都有几个小时是不可用的。</p>
<p><img src="/img/hystrix/依赖服务的故障导致服务被拖垮以及故障的蔓延.png" alt="依赖服务的故障导致服务被拖垮以及故障的蔓延"></p>
<h1 id="Hystrix的更加细节的设计原则"><a href="#Hystrix的更加细节的设计原则" class="headerlink" title="Hystrix的更加细节的设计原则"></a>Hystrix的更加细节的设计原则</h1><ol>
<li>阻止任何一个依赖服务耗尽所有的资源，比如tomcat中的所有线程资源</li>
<li>避免请求排队和积压，采用限流和fail fast来控制故障</li>
<li>提供fallback降级机制来应对故障</li>
<li>使用资源隔离技术，比如bulkhead（舱壁隔离技术），swimlane（泳道技术），circuit breaker（短路技术），来限制任何一个依赖服务的故障的影响</li>
<li>通过近实时的统计/监控/报警功能，来提高故障发现的速度</li>
<li>通过近实时的属性和配置热修改功能，来提高故障处理和恢复的速度</li>
<li>保护依赖服务调用的所有故障情况，而不仅仅只是网络故障情况</li>
</ol>
<h1 id="Hystrix的实现"><a href="#Hystrix的实现" class="headerlink" title="Hystrix的实现"></a>Hystrix的实现</h1><ol>
<li>通过HystrixCommand或者HystrixObservableCommand来封装对外部依赖的访问请求，这个访问请求一般会运行在独立的线程中，资源隔离</li>
<li>对于超出我们设定阈值的服务调用，直接进行超时，不允许其耗费过长时间阻塞住。这个超时时间默认是99.5%的访问时间，但是一般我们可以自己设置一下</li>
<li>为每一个依赖服务维护一个独立的线程池，或者是semaphore，当线程池已满时，直接拒绝对这个服务的调用</li>
<li>对依赖服务的调用的成功次数，失败次数，拒绝次数，超时次数，进行统计</li>
<li>如果对一个依赖服务的调用失败次数超过了一定的阈值，自动进行熔断，在一定时间内对该服务的调用直接降级，一段时间后再自动尝试恢复</li>
<li>当一个服务调用出现失败，被拒绝，超时，短路等异常情况时，自动调用fallback降级机制</li>
<li>对属性和配置的修改提供近实时的支持</li>
</ol>
<p><img src="/img/hystrix/资源隔离如何保护依赖服务的故障不要拖垮整个系统.png" alt="资源隔离如何保护依赖服务的故障不要拖垮整个系统"></p>
<h1 id="Hystrix项目实战"><a href="#Hystrix项目实战" class="headerlink" title="Hystrix项目实战"></a>Hystrix项目实战</h1><h2 id="背景"><a href="#背景" class="headerlink" title="背景"></a>背景</h2><p>商品详情页服务和缓存服务，模拟缓存更新时如何使用hystrix。</p>
<p><strong>缓存服务</strong></p>
<p><a href="https://github.com/sail-y/eshop-cache-ha" target="_blank" rel="noopener">https://github.com/sail-y/eshop-cache-ha</a></p>
<p><strong>商品服务</strong></p>
<p><a href="https://github.com/sail-y/eshop-product-ha" target="_blank" rel="noopener">https://github.com/sail-y/eshop-product-ha</a></p>
<h2 id="商品服务接口导致缓存服务资源耗尽的问题"><a href="#商品服务接口导致缓存服务资源耗尽的问题" class="headerlink" title="商品服务接口导致缓存服务资源耗尽的问题"></a>商品服务接口导致缓存服务资源耗尽的问题</h2><p><img src="/img/hystrix/商品服务接口导致缓存服务资源耗尽的问题.png" alt="商品服务接口导致缓存服务资源耗尽的问题"></p>
<h2 id="基于线程池的资源隔离"><a href="#基于线程池的资源隔离" class="headerlink" title="基于线程池的资源隔离"></a>基于线程池的资源隔离</h2><p>hystrix进行资源隔离，其实是提供了一个command抽象。把对某一个依赖服务的所有调用请求全部隔离在同一份资源池内，对这个依赖服务的所有调用请求，全部走这个资源池内的资源，不会去用其他的资源了，这个就叫做资源隔离。</p>
<p>hystrix最最基本的资源隔离的技术，<strong>线程池隔离技术</strong>。对某一个依赖服务，商品服务，所有的调用请求，全部隔离到一个线程池内，对商品服务的每次调用请求都封装在一个command里面。每个command（每次服务调用请求）都是使用线程池内的一个线程去执行的，所以哪怕是对这个依赖服务（商品服务）同时发起的调用量已经到了1000了，但是线程池内就10个线程，最多就只会用这10个线程去执行。</p>
<p>不会出现对商品服务的请求，因为接口调用延迟将tomcat内部所有的线程资源全部耗尽。目的是为了保护不要因为某一个依赖服务的故障，导致耗尽了缓存服务中的所有的线程资源去执行。</p>
<h3 id="HystrixCommand：是用来获取一条数据的"><a href="#HystrixCommand：是用来获取一条数据的" class="headerlink" title="HystrixCommand：是用来获取一条数据的"></a>HystrixCommand：是用来获取一条数据的</h3><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">GetProductInfoCommand</span> <span class="keyword">extends</span> <span class="title">HystrixCommand</span>&lt;<span class="title">ProductInfo</span>&gt; </span>&#123;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">private</span> Long productId;</span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="title">GetProductInfoCommand</span><span class="params">(Long productId)</span> </span>&#123;</span><br><span class="line">        <span class="keyword">super</span>(HystrixCommandGroupKey.Factory.asKey(<span class="string">"GetProductInfoCommandGroup"</span>));</span><br><span class="line">        <span class="keyword">this</span>.productId = productId;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="meta">@Override</span></span><br><span class="line">    <span class="function"><span class="keyword">protected</span> ProductInfo <span class="title">run</span><span class="params">()</span> </span>&#123;</span><br><span class="line"></span><br><span class="line">        String url = <span class="string">"http://localhost:8082/getProductInfo?productId="</span> + productId;</span><br><span class="line">        String response = HttpUtil.get(url);</span><br><span class="line">        System.out.println(response);</span><br><span class="line">        <span class="keyword">return</span> JSON.parseObject(response, ProductInfo.class);</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>test:</p>
<p><a href="http://localhost:8081/getProductInfo?productId=1" target="_blank" rel="noopener">http://localhost:8081/getProductInfo?productId=1</a></p>
<h3 id="HystrixObservableCommand：是设计用来获取多条数据的"><a href="#HystrixObservableCommand：是设计用来获取多条数据的" class="headerlink" title="HystrixObservableCommand：是设计用来获取多条数据的"></a>HystrixObservableCommand：是设计用来获取多条数据的</h3><p>controller:</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta">@RequestMapping</span>(<span class="string">"/getProductInfos"</span>)</span><br><span class="line"><span class="function"><span class="keyword">public</span> String <span class="title">getProductInfos</span><span class="params">(String productIds)</span> </span>&#123;</span><br><span class="line">    HystrixObservableCommand&lt;ProductInfo&gt; getProductInfosCommand = <span class="keyword">new</span> GetProductInfosCommand(productIds.split(<span class="string">","</span>));</span><br><span class="line">    Observable&lt;ProductInfo&gt; observable = getProductInfosCommand.observe();</span><br><span class="line">    observable.subscribe(<span class="keyword">new</span> Observer&lt;ProductInfo&gt;()&#123;</span><br><span class="line">        <span class="meta">@Override</span></span><br><span class="line">        <span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">onCompleted</span><span class="params">()</span> </span>&#123;</span><br><span class="line">            log.info(<span class="string">"获取完了所有的商品数据"</span>);</span><br><span class="line">        &#125;</span><br><span class="line"></span><br><span class="line">        <span class="meta">@Override</span></span><br><span class="line">        <span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">onError</span><span class="params">(Throwable throwable)</span> </span>&#123;</span><br><span class="line">            throwable.printStackTrace();</span><br><span class="line">        &#125;</span><br><span class="line"></span><br><span class="line">        <span class="meta">@Override</span></span><br><span class="line">        <span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">onNext</span><span class="params">(ProductInfo productInfo)</span> </span>&#123;</span><br><span class="line">            log.info(productInfo.toString());</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;);</span><br><span class="line"></span><br><span class="line">    <span class="keyword">return</span> <span class="string">"success"</span>;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>command:</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">GetProductInfosCommand</span> <span class="keyword">extends</span> <span class="title">HystrixObservableCommand</span>&lt;<span class="title">ProductInfo</span>&gt; </span>&#123;</span><br><span class="line">    <span class="keyword">private</span> String[] productIds;</span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="title">GetProductInfosCommand</span><span class="params">(String[] productIds)</span> </span>&#123;</span><br><span class="line">        <span class="keyword">super</span>(HystrixCommandGroupKey.Factory.asKey(<span class="string">"GetProductInfoCommandGroup"</span>));</span><br><span class="line">        <span class="keyword">this</span>.productIds = productIds;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="meta">@Override</span></span><br><span class="line">    <span class="function"><span class="keyword">protected</span> Observable&lt;ProductInfo&gt; <span class="title">construct</span><span class="params">()</span> </span>&#123;</span><br><span class="line"></span><br><span class="line">        <span class="keyword">return</span> Observable.&lt;ProductInfo&gt;create(observer -&gt; &#123;</span><br><span class="line">            <span class="keyword">try</span> &#123;</span><br><span class="line">                <span class="keyword">if</span> (!observer.isUnsubscribed()) &#123;</span><br><span class="line">                    <span class="keyword">for</span> (String productId : productIds) &#123;</span><br><span class="line">                        String url = <span class="string">"http://localhost:8082/getProductInfo?productId="</span> + productId;</span><br><span class="line">                        String response = HttpUtil.get(url);</span><br><span class="line">                        ProductInfo productInfo = JSON.parseObject(response, ProductInfo.class);</span><br><span class="line">                        observer.onNext(productInfo);</span><br><span class="line"></span><br><span class="line">                    &#125;</span><br><span class="line">                    observer.onCompleted();</span><br><span class="line">                &#125;</span><br><span class="line">            &#125; <span class="keyword">catch</span> (Exception e) &#123;</span><br><span class="line">                observer.onError(e);</span><br><span class="line">            &#125;</span><br><span class="line">        &#125;).subscribeOn(Schedulers.io());</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>test:</p>
<p><a href="http://localhost:8081/getProductInfos?productId=1,2,3" target="_blank" rel="noopener">http://localhost:8081/getProductInfos?productId=1,2,3</a></p>
<h3 id="command的四种调用方式"><a href="#command的四种调用方式" class="headerlink" title="command的四种调用方式"></a>command的四种调用方式</h3><p>同步：new CommandHelloWorld(“World”).execute()，new ObservableCommandHelloWorld(“World”).toBlocking().toFuture().get()</p>
<p>异步：new CommandHelloWorld(“World”).queue()，new ObservableCommandHelloWorld(“World”).toBlocking().toFuture()</p>
<p>立即执行： observe()：hot，已经执行过了</p>
<p>订阅： toObservable(): cold，还没执行过</p>
<h2 id="基于信号量的资源隔离"><a href="#基于信号量的资源隔离" class="headerlink" title="基于信号量的资源隔离"></a>基于信号量的资源隔离</h2><p><img src="/img/hystrix/信号量的资源隔离与限流的说明.png" alt="信号量的资源隔离与限流的说明"></p>
<p>信号量跟线程池两种资源隔离的技术的区别：</p>
<p><img src="/img/hystrix/线程池隔离和信号量隔离的原理以及区别.png" alt="线程池隔离和信号量隔离的原理以及区别"></p>
<h2 id="线程池隔离技术和信号量隔离技术，分别在什么样的场景下去使用"><a href="#线程池隔离技术和信号量隔离技术，分别在什么样的场景下去使用" class="headerlink" title="线程池隔离技术和信号量隔离技术，分别在什么样的场景下去使用?"></a>线程池隔离技术和信号量隔离技术，分别在什么样的场景下去使用?</h2><p>线程池：适合99%场景，线程池一般处理对依赖服务的网络请求的调用和访问，timeout这种问题。</p>
<p>信号量：适合不是对外部依赖的访问，而是对内部的一些比较复杂的业务逻辑的访问，但是像这种访问系统内部的代码，其实不涉及任何的网络请求。那么只要做信号量的普通限流就可以了，因为不需要去捕获timeout类似的问题，如果算法+数据结构的效率不是太高，并发量突然太高，因为这里稍微耗时一些，导致很多线程卡在这里的话是不太好的。所以进行一个基本的资源隔离和访问，避免内部复杂的低效率的代码，导致大量的线程被hang住。</p>
<p><strong>采用信号量技术进行资源隔离与限流</strong></p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">super</span>(Setter.withGroupKey(HystrixCommandGroupKey.Factory.asKey(<span class="string">"ExampleGroup"</span>))</span><br><span class="line">        .andCommandPropertiesDefaults(HystrixCommandProperties.Setter()</span><br><span class="line">               .withExecutionIsolationStrategy(ExecutionIsolationStrategy.SEMAPHORE)));</span><br></pre></td></tr></table></figure>
<h2 id="资源隔离策略配置"><a href="#资源隔离策略配置" class="headerlink" title="资源隔离策略配置"></a>资源隔离策略配置</h2><p>现在我们知道有线程池（THREAD）和信号量（SEMAPHORE）两种隔离方式。除了选择隔离方式，hystrix还支持对隔离策略进行一些细粒度的配置。</p>
<p>默认的策略就是线程池</p>
<p>线程池其实最大的好处就是对于网络访问请求，如果有超时的话，可以避免调用线程阻塞住</p>
<p>而使用信号量的场景，通常是针对超大并发量的场景下，每个服务实例每秒都几百的QPS，那么此时你用线程池的话，线程一般不会太多，可能撑不住那么高的并发，如果要撑住，可能要耗费大量的线程资源，那么就是用信号量，来进行限流保护</p>
<p>一般用信号量常见于那种基于纯内存的一些业务逻辑服务，而不涉及到任何网络访问请求</p>
<p>netflix有100+的command运行在40+的线程池中，只有少数command是不运行在线程池中的，就是从纯内存中获取一些元数据，或者是对多个command包装起来的facacde command，是用信号量限流的</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">// to use thread isolation</span></span><br><span class="line">HystrixCommandProperties.Setter()</span><br><span class="line">   .withExecutionIsolationStrategy(ExecutionIsolationStrategy.THREAD)</span><br><span class="line"><span class="comment">// to use semaphore isolation</span></span><br><span class="line">HystrixCommandProperties.Setter()</span><br><span class="line">   .withExecutionIsolationStrategy(ExecutionIsolationStrategy.SEMAPHORE)</span><br></pre></td></tr></table></figure>
<h3 id="command名称和command组"><a href="#command名称和command组" class="headerlink" title="command名称和command组"></a>command名称和command组</h3><p>每个command都可以设置一个自己的名称，同时可以设置一个自己的组。</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">private</span> <span class="keyword">static</span> <span class="keyword">final</span> Setter cachedSetter = </span><br><span class="line">    Setter.withGroupKey(HystrixCommandGroupKey.Factory.asKey(<span class="string">"ExampleGroup"</span>))</span><br><span class="line">        .andCommandKey(HystrixCommandKey.Factory.asKey(<span class="string">"HelloWorld"</span>));    </span><br><span class="line"></span><br><span class="line"><span class="function"><span class="keyword">public</span> <span class="title">CommandHelloWorld</span><span class="params">(String name)</span> </span>&#123;</span><br><span class="line">    <span class="keyword">super</span>(cachedSetter);</span><br><span class="line">    <span class="keyword">this</span>.name = name;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>command group，是一个非常重要的概念，默认情况下，因为就是通过command group来定义一个线程池的，而且还会通过command group来聚合一些监控和报警信息。同一个command group中的请求，都会进入同一个线程池中。</p>
<h3 id="command线程池"><a href="#command线程池" class="headerlink" title="command线程池"></a>command线程池</h3><p>threadpool key代表了一个HystrixThreadPool，用来进行统一监控，统计，缓存。默认的threadpool key就是command group名称。每个command都会跟它的threadpool key对应的thread pool绑定在一起。如果不想直接用command group，也可以手动设置thread pool name。</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">public</span> <span class="title">CommandHelloWorld</span><span class="params">(String name)</span> </span>&#123;</span><br><span class="line">    <span class="keyword">super</span>(Setter.withGroupKey(HystrixCommandGroupKey.Factory.asKey(<span class="string">"ExampleGroup"</span>))</span><br><span class="line">            .andCommandKey(HystrixCommandKey.Factory.asKey(<span class="string">"HelloWorld"</span>))</span><br><span class="line">            .andThreadPoolKey(HystrixThreadPoolKey.Factory.asKey(<span class="string">"HelloWorldPool"</span>)));</span><br><span class="line">    <span class="keyword">this</span>.name = name;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>command threadpool -&gt; command group -&gt; command key</p>
<ul>
<li>command key：代表了一类command，一般来说代表了底层的依赖服务的一个接口。</li>
<li>command group：代表了某一个底层的依赖服务，一个依赖服务可能会暴露出来多个接口，每个接口就是一个command key。在逻辑上去组织起来一堆command key的调用，统计信息、成功次数、timeout超时次数、失败次数等等，可以看到某一个服务整体的一些访问情况。一般推荐是根据一个服务去划分出一个线程池，command key默认都是属于同一个线程池的。</li>
</ul>
<p>比如以一个服务为粒度，估算出来这个服务每秒的所有接口加起来的整体QPS在100左右。调用目标服务的当前服务部署了10个服务实例，每个服务实例上给一个线程池，线程数量大概在10个左右，就可以满足对目标服务的整体的访问QPS大概在每秒100左右需求了。</p>
<p>还有一种场景，就是command group对应的服务的接口访问量差别很大。然后就希望做一些细粒度的资源隔离，针对同一个服务的不同接口，使用不同的线程池。</p>
<p>之前的模式是： command key -&gt; command group</p>
<p>我们可以针对每个command单独设置threadpool key：command key -&gt; 自己的threadpool key</p>
<p>这样从逻辑上来说多个command key是属于一个command group的，在做统计的时候会放在一起统计。但是每个command key有自己的线程池，每个接口有自己的线程池去做资源隔离和限流。</p>
<h3 id="设置线程池大小"><a href="#设置线程池大小" class="headerlink" title="设置线程池大小"></a>设置线程池大小</h3><p>Hystrix默认的线程池大小是10，可以通过下面的代码进行设置。</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line">HystrixThreadPoolProperties.Setter()</span><br><span class="line">   .withCoreSize(<span class="keyword">int</span> value)</span><br></pre></td></tr></table></figure>
<p>一般来说默认的10个已经够了。</p>
<h3 id="queueSizeRejectionThreshold"><a href="#queueSizeRejectionThreshold" class="headerlink" title="queueSizeRejectionThreshold"></a>queueSizeRejectionThreshold</h3><p>线程池是10个，如果还有请求过来，默认可以排队的线程是5个。超过5个以后多余的请求进来，就会被线程池拒绝掉，抛出异常。</p>
<p>默认值是5，可以通过下面代码修改：</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line">HystrixThreadPoolProperties.Setter()</span><br><span class="line">   .withQueueSizeRejectionThreshold(<span class="keyword">int</span> value)</span><br></pre></td></tr></table></figure>
<h3 id="execution-isolation-semaphore-maxConcurrentRequests"><a href="#execution-isolation-semaphore-maxConcurrentRequests" class="headerlink" title="execution.isolation.semaphore.maxConcurrentRequests"></a>execution.isolation.semaphore.maxConcurrentRequests</h3><p>设置使用SEMAPHORE隔离策略的时候，允许访问的最大并发量，超过这个最大并发量，请求直接被reject。这个并发量的设置跟线程池大小的设置应该是类似的，但是基于信号量的话性能会好很多，而且hystrix框架本身的开销会小很多。</p>
<p>默认值是10，不能设置得太大，因为信号量是基于调用线程去执行command的，而且不能从timeout中抽离，因此一旦设置的太大，而且有延时发生，可能瞬间导致tomcat本身的线程资源本占满。</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line">HystrixCommandProperties.Setter()</span><br><span class="line">   .withExecutionIsolationSemaphoreMaxConcurrentRequests(<span class="keyword">int</span> value)</span><br></pre></td></tr></table></figure>
<p>Hystrix的基本使用已经差不多是这样了，后面再有一篇文章，分析hystrix的流程和原理。</p>

      
    </div>

    

    
    
    

    

    
      <div>
        <div style="padding: 10px 0; margin: 20px auto; width: 90%; text-align: center;">
  <div>坚持原创技术分享，您的支持将鼓励我继续创作！</div>
  <button id="rewardButton" disable="enable" onclick="var qr = document.getElementById('QR'); if (qr.style.display === 'none') {qr.style.display='block';} else {qr.style.display='none'}">
    <span>打赏</span>
  </button>
  <div id="QR" style="display: none;">

    
      <div id="wechat" style="display: inline-block">
        <img id="wechat_qr" src="/img/donate/wechatpay.jpeg" alt="杨帆 微信支付"/>
        <p>微信支付</p>
      </div>
    

    
      <div id="alipay" style="display: inline-block">
        <img id="alipay_qr" src="/img/donate/alipay.jpeg" alt="杨帆 支付宝"/>
        <p>支付宝</p>
      </div>
    

    

  </div>
</div>

      </div>
    

    

    <footer class="post-footer">
      
        <div class="post-tags">
          
            <a href="/tags/spring-cloud/" rel="tag"># spring-cloud</a>
          
            <a href="/tags/hystrix/" rel="tag"># hystrix</a>
          
        </div>
      

      
      
      

      
        <div class="post-nav">
          <div class="post-nav-next post-nav-item">
            
              <a href="/2018/02/22/cache05/" rel="next" title="高可用缓存架构实战5-缓存预热">
                <i class="fa fa-chevron-left"></i> 高可用缓存架构实战5-缓存预热
              </a>
            
          </div>

          <span class="post-nav-divider"></span>

          <div class="post-nav-prev post-nav-item">
            
              <a href="/2018/03/26/hystrix02/" rel="prev" title="Hystrix流程和原理讲解">
                Hystrix流程和原理讲解 <i class="fa fa-chevron-right"></i>
              </a>
            
          </div>
        </div>
      

      
      
    </footer>
  </div>
  
  
  
  </article>



    <div class="post-spread">
      
    </div>
  </div>


          </div>
          

  
    <div class="comments" id="comments">
      <div id="lv-container" data-id="city" data-uid="MTAyMC8yOTk2Ni82NTMx"></div>
    </div>

  



        </div>
        
          
  
  <div class="sidebar-toggle">
    <div class="sidebar-toggle-line-wrap">
      <span class="sidebar-toggle-line sidebar-toggle-line-first"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-middle"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-last"></span>
    </div>
  </div>

  <aside id="sidebar" class="sidebar">
    
    <div class="sidebar-inner">

      

      
        <ul class="sidebar-nav motion-element">
          <li class="sidebar-nav-toc sidebar-nav-active" data-target="post-toc-wrap">
            文章目录
          </li>
          <li class="sidebar-nav-overview" data-target="site-overview-wrap">
            站点概览
          </li>
        </ul>
      

      <section class="site-overview-wrap sidebar-panel">
        <div class="site-overview">
          <div class="site-author motion-element" itemprop="author" itemscope itemtype="http://schema.org/Person">
            
              <img class="site-author-image" itemprop="image"
                src="/img/photo/bug.png"
                alt="杨帆" />
            
              <p class="site-author-name" itemprop="name">杨帆</p>
              <p class="site-description motion-element" itemprop="description">记录工作和学习中遇到的问题</p>
          </div>

          
            <nav class="site-state motion-element">
              
                <div class="site-state-item site-state-posts">
                
                  <a href="/archives/">
                
                    <span class="site-state-item-count">107</span>
                    <span class="site-state-item-name">日志</span>
                  </a>
                </div>
              

              
                
                
                <div class="site-state-item site-state-categories">
                  <a href="/categories/index.html">
                    
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                    <span class="site-state-item-count">18</span>
                    <span class="site-state-item-name">分类</span>
                  </a>
                </div>
              

              
                
                
                <div class="site-state-item site-state-tags">
                  <a href="/tags/index.html">
                    
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                    <span class="site-state-item-count">38</span>
                    <span class="site-state-item-name">标签</span>
                  </a>
                </div>
              
            </nav>
          

          
            <div class="feed-link motion-element">
              <a href="/atom.xml" rel="alternate">
                <i class="fa fa-rss"></i>
                RSS
              </a>
            </div>
          

          
            <div class="links-of-author motion-element">
              
                <span class="links-of-author-item">
                  <a href="https://github.com/sail-y" target="_blank" title="GitHub"><i class="fa fa-fw fa-github"></i>GitHub</a>
                  
                </span>
              
                <span class="links-of-author-item">
                  <a href="https://weibo.com/338632221" target="_blank" title="微博"><i class="fa fa-fw fa-globe"></i>微博</a>
                  
                </span>
              
            </div>
          

          
          

          
          

          
            
          
          

        </div>
      </section>

      
      <!--noindex-->
        <section class="post-toc-wrap motion-element sidebar-panel sidebar-panel-active">
          <div class="post-toc">

            
              
            

            
              <div class="post-toc-content"><ol class="nav"><li class="nav-item nav-level-1"><a class="nav-link" href="#Hystrix是什么？"><span class="nav-number">1.</span> <span class="nav-text">Hystrix是什么？</span></a></li><li class="nav-item nav-level-1"><a class="nav-link" href="#Hystrix的历史"><span class="nav-number">2.</span> <span class="nav-text">Hystrix的历史</span></a></li><li class="nav-item nav-level-1"><a class="nav-link" href="#Hystrix的设计原则"><span class="nav-number">3.</span> <span class="nav-text">Hystrix的设计原则</span></a></li><li class="nav-item nav-level-1"><a class="nav-link" href="#Hystrix要解决的问题"><span class="nav-number">4.</span> <span class="nav-text">Hystrix要解决的问题</span></a></li><li class="nav-item nav-level-1"><a class="nav-link" href="#Hystrix的更加细节的设计原则"><span class="nav-number">5.</span> <span class="nav-text">Hystrix的更加细节的设计原则</span></a></li><li class="nav-item nav-level-1"><a class="nav-link" href="#Hystrix的实现"><span class="nav-number">6.</span> <span class="nav-text">Hystrix的实现</span></a></li><li class="nav-item nav-level-1"><a class="nav-link" href="#Hystrix项目实战"><span class="nav-number">7.</span> <span class="nav-text">Hystrix项目实战</span></a><ol class="nav-child"><li class="nav-item nav-level-2"><a class="nav-link" href="#背景"><span class="nav-number">7.1.</span> <span class="nav-text">背景</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#商品服务接口导致缓存服务资源耗尽的问题"><span class="nav-number">7.2.</span> <span class="nav-text">商品服务接口导致缓存服务资源耗尽的问题</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#基于线程池的资源隔离"><span class="nav-number">7.3.</span> <span class="nav-text">基于线程池的资源隔离</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#HystrixCommand：是用来获取一条数据的"><span class="nav-number">7.3.1.</span> <span class="nav-text">HystrixCommand：是用来获取一条数据的</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#HystrixObservableCommand：是设计用来获取多条数据的"><span class="nav-number">7.3.2.</span> <span class="nav-text">HystrixObservableCommand：是设计用来获取多条数据的</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#command的四种调用方式"><span class="nav-number">7.3.3.</span> <span class="nav-text">command的四种调用方式</span></a></li></ol></li><li class="nav-item nav-level-2"><a class="nav-link" href="#基于信号量的资源隔离"><span class="nav-number">7.4.</span> <span class="nav-text">基于信号量的资源隔离</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#线程池隔离技术和信号量隔离技术，分别在什么样的场景下去使用"><span class="nav-number">7.5.</span> <span class="nav-text">线程池隔离技术和信号量隔离技术，分别在什么样的场景下去使用?</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#资源隔离策略配置"><span class="nav-number">7.6.</span> <span class="nav-text">资源隔离策略配置</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#command名称和command组"><span class="nav-number">7.6.1.</span> <span class="nav-text">command名称和command组</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#command线程池"><span class="nav-number">7.6.2.</span> <span class="nav-text">command线程池</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#设置线程池大小"><span class="nav-number">7.6.3.</span> <span class="nav-text">设置线程池大小</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#queueSizeRejectionThreshold"><span class="nav-number">7.6.4.</span> <span class="nav-text">queueSizeRejectionThreshold</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#execution-isolation-semaphore-maxConcurrentRequests"><span class="nav-number">7.6.5.</span> <span class="nav-text">execution.isolation.semaphore.maxConcurrentRequests</span></a></li></ol></li></ol></li></ol></div>
            

          </div>
        </section>
      <!--/noindex-->
      

      

    </div>
  </aside>


        
      </div>
    </main>

    <footer id="footer" class="footer">
      <div class="footer-inner">
        <div class="copyright">&copy; 2015 &mdash; <span itemprop="copyrightYear">2018</span>
  <span class="with-love" id="animate">
    <i class="fa fa-user"></i>
  </span>
  <span class="author" itemprop="copyrightHolder">杨帆</span>

  

  
</div>




  <div class="powered-by">由 <a class="theme-link" target="_blank" href="https://hexo.io">Hexo</a> 强力驱动 v3.7.1</div>



  <span class="post-meta-divider">|</span>



  <div class="theme-info">主题 &mdash; <a class="theme-link" target="_blank" href="https://github.com/theme-next/hexo-theme-next">NexT.Gemini</a> v6.1.0</div>




        
<div class="busuanzi-count">
  <script async src="https://dn-lbstatics.qbox.me/busuanzi/2.3/busuanzi.pure.mini.js"></script>

  
    <span class="site-uv" title="总访客量">
      <i class="fa fa-user"></i>
      <span class="busuanzi-value" id="busuanzi_value_site_uv"></span>
    </span>
  

  
    <span class="site-pv" title="总访问量">
      <i class="fa fa-eye"></i>
      <span class="busuanzi-value" id="busuanzi_value_site_pv"></span>
    </span>
  
</div>









        
      </div>
    </footer>

    
      <div class="back-to-top">
        <i class="fa fa-arrow-up"></i>
        
      </div>
    

    

  </div>

  

<script type="text/javascript">
  if (Object.prototype.toString.call(window.Promise) !== '[object Function]') {
    window.Promise = null;
  }
</script>














  



  
  











  
  
    <script type="text/javascript" src="/lib/jquery/index.js?v=2.1.3"></script>
  

  
  
    <script type="text/javascript" src="/lib/velocity/velocity.min.js?v=1.2.1"></script>
  

  
  
    <script type="text/javascript" src="/lib/velocity/velocity.ui.min.js?v=1.2.1"></script>
  

  
  
    <script type="text/javascript" src="/lib/canvas-nest/canvas-nest.min.js"></script>
  

  
  
    <script type="text/javascript" src="/lib/three/three.min.js"></script>
  

  
  
    <script type="text/javascript" src="/lib/three/three-waves.min.js"></script>
  


  


  <script type="text/javascript" src="/js/src/utils.js?v=6.1.0"></script>

  <script type="text/javascript" src="/js/src/motion.js?v=6.1.0"></script>



  
  


  <script type="text/javascript" src="/js/src/affix.js?v=6.1.0"></script>

  <script type="text/javascript" src="/js/src/schemes/pisces.js?v=6.1.0"></script>



  
  <script type="text/javascript" src="/js/src/scrollspy.js?v=6.1.0"></script>
<script type="text/javascript" src="/js/src/post-details.js?v=6.1.0"></script>



  


  <script type="text/javascript" src="/js/src/bootstrap.js?v=6.1.0"></script>



  



	





  





  
    <script type="text/javascript">
      (function(d, s) {
        var j, e = d.getElementsByTagName(s)[0];
        if (typeof LivereTower === 'function') { return; }
        j = d.createElement(s);
        j.src = 'https://cdn-city.livere.com/js/embed.dist.js';
        j.async = true;
        e.parentNode.insertBefore(j, e);
      })(document, 'script');
    </script>
  










  

  <script type="text/javascript">
    // Popup Window;
    var isfetched = false;
    var isXml = true;
    // Search DB path;
    var search_path = "search.xml";
    if (search_path.length === 0) {
      search_path = "search.xml";
    } else if (/json$/i.test(search_path)) {
      isXml = false;
    }
    var path = "/" + search_path;
    // monitor main search box;

    var onPopupClose = function (e) {
      $('.popup').hide();
      $('#local-search-input').val('');
      $('.search-result-list').remove();
      $('#no-result').remove();
      $(".local-search-pop-overlay").remove();
      $('body').css('overflow', '');
    }

    function proceedsearch() {
      $("body")
        .append('<div class="search-popup-overlay local-search-pop-overlay"></div>')
        .css('overflow', 'hidden');
      $('.search-popup-overlay').click(onPopupClose);
      $('.popup').toggle();
      var $localSearchInput = $('#local-search-input');
      $localSearchInput.attr("autocapitalize", "none");
      $localSearchInput.attr("autocorrect", "off");
      $localSearchInput.focus();
    }

    // search function;
    var searchFunc = function(path, search_id, content_id) {
      'use strict';

      // start loading animation
      $("body")
        .append('<div class="search-popup-overlay local-search-pop-overlay">' +
          '<div id="search-loading-icon">' +
          '<i class="fa fa-spinner fa-pulse fa-5x fa-fw"></i>' +
          '</div>' +
          '</div>')
        .css('overflow', 'hidden');
      $("#search-loading-icon").css('margin', '20% auto 0 auto').css('text-align', 'center');

      

      $.ajax({
        url: path,
        dataType: isXml ? "xml" : "json",
        async: true,
        success: function(res) {
          // get the contents from search data
          isfetched = true;
          $('.popup').detach().appendTo('.header-inner');
          var datas = isXml ? $("entry", res).map(function() {
            return {
              title: $("title", this).text(),
              content: $("content",this).text(),
              url: $("url" , this).text()
            };
          }).get() : res;
          var input = document.getElementById(search_id);
          var resultContent = document.getElementById(content_id);
          var inputEventFunction = function() {
            var searchText = input.value.trim().toLowerCase();
            var keywords = searchText.split(/[\s\-]+/);
            if (keywords.length > 1) {
              keywords.push(searchText);
            }
            var resultItems = [];
            if (searchText.length > 0) {
              // perform local searching
              datas.forEach(function(data) {
                var isMatch = false;
                var hitCount = 0;
                var searchTextCount = 0;
                var title = data.title.trim();
                var titleInLowerCase = title.toLowerCase();
                var content = data.content.trim().replace(/<[^>]+>/g,"");
                
                var contentInLowerCase = content.toLowerCase();
                var articleUrl = decodeURIComponent(data.url);
                var indexOfTitle = [];
                var indexOfContent = [];
                // only match articles with not empty titles
                if(title != '') {
                  keywords.forEach(function(keyword) {
                    function getIndexByWord(word, text, caseSensitive) {
                      var wordLen = word.length;
                      if (wordLen === 0) {
                        return [];
                      }
                      var startPosition = 0, position = [], index = [];
                      if (!caseSensitive) {
                        text = text.toLowerCase();
                        word = word.toLowerCase();
                      }
                      while ((position = text.indexOf(word, startPosition)) > -1) {
                        index.push({position: position, word: word});
                        startPosition = position + wordLen;
                      }
                      return index;
                    }

                    indexOfTitle = indexOfTitle.concat(getIndexByWord(keyword, titleInLowerCase, false));
                    indexOfContent = indexOfContent.concat(getIndexByWord(keyword, contentInLowerCase, false));
                  });
                  if (indexOfTitle.length > 0 || indexOfContent.length > 0) {
                    isMatch = true;
                    hitCount = indexOfTitle.length + indexOfContent.length;
                  }
                }

                // show search results

                if (isMatch) {
                  // sort index by position of keyword

                  [indexOfTitle, indexOfContent].forEach(function (index) {
                    index.sort(function (itemLeft, itemRight) {
                      if (itemRight.position !== itemLeft.position) {
                        return itemRight.position - itemLeft.position;
                      } else {
                        return itemLeft.word.length - itemRight.word.length;
                      }
                    });
                  });

                  // merge hits into slices

                  function mergeIntoSlice(text, start, end, index) {
                    var item = index[index.length - 1];
                    var position = item.position;
                    var word = item.word;
                    var hits = [];
                    var searchTextCountInSlice = 0;
                    while (position + word.length <= end && index.length != 0) {
                      if (word === searchText) {
                        searchTextCountInSlice++;
                      }
                      hits.push({position: position, length: word.length});
                      var wordEnd = position + word.length;

                      // move to next position of hit

                      index.pop();
                      while (index.length != 0) {
                        item = index[index.length - 1];
                        position = item.position;
                        word = item.word;
                        if (wordEnd > position) {
                          index.pop();
                        } else {
                          break;
                        }
                      }
                    }
                    searchTextCount += searchTextCountInSlice;
                    return {
                      hits: hits,
                      start: start,
                      end: end,
                      searchTextCount: searchTextCountInSlice
                    };
                  }

                  var slicesOfTitle = [];
                  if (indexOfTitle.length != 0) {
                    slicesOfTitle.push(mergeIntoSlice(title, 0, title.length, indexOfTitle));
                  }

                  var slicesOfContent = [];
                  while (indexOfContent.length != 0) {
                    var item = indexOfContent[indexOfContent.length - 1];
                    var position = item.position;
                    var word = item.word;
                    // cut out 100 characters
                    var start = position - 20;
                    var end = position + 80;
                    if(start < 0){
                      start = 0;
                    }
                    if (end < position + word.length) {
                      end = position + word.length;
                    }
                    if(end > content.length){
                      end = content.length;
                    }
                    slicesOfContent.push(mergeIntoSlice(content, start, end, indexOfContent));
                  }

                  // sort slices in content by search text's count and hits' count

                  slicesOfContent.sort(function (sliceLeft, sliceRight) {
                    if (sliceLeft.searchTextCount !== sliceRight.searchTextCount) {
                      return sliceRight.searchTextCount - sliceLeft.searchTextCount;
                    } else if (sliceLeft.hits.length !== sliceRight.hits.length) {
                      return sliceRight.hits.length - sliceLeft.hits.length;
                    } else {
                      return sliceLeft.start - sliceRight.start;
                    }
                  });

                  // select top N slices in content

                  var upperBound = parseInt('1');
                  if (upperBound >= 0) {
                    slicesOfContent = slicesOfContent.slice(0, upperBound);
                  }

                  // highlight title and content

                  function highlightKeyword(text, slice) {
                    var result = '';
                    var prevEnd = slice.start;
                    slice.hits.forEach(function (hit) {
                      result += text.substring(prevEnd, hit.position);
                      var end = hit.position + hit.length;
                      result += '<b class="search-keyword">' + text.substring(hit.position, end) + '</b>';
                      prevEnd = end;
                    });
                    result += text.substring(prevEnd, slice.end);
                    return result;
                  }

                  var resultItem = '';

                  if (slicesOfTitle.length != 0) {
                    resultItem += "<li><a href='" + articleUrl + "' class='search-result-title'>" + highlightKeyword(title, slicesOfTitle[0]) + "</a>";
                  } else {
                    resultItem += "<li><a href='" + articleUrl + "' class='search-result-title'>" + title + "</a>";
                  }

                  slicesOfContent.forEach(function (slice) {
                    resultItem += "<a href='" + articleUrl + "'>" +
                      "<p class=\"search-result\">" + highlightKeyword(content, slice) +
                      "...</p>" + "</a>";
                  });

                  resultItem += "</li>";
                  resultItems.push({
                    item: resultItem,
                    searchTextCount: searchTextCount,
                    hitCount: hitCount,
                    id: resultItems.length
                  });
                }
              })
            };
            if (keywords.length === 1 && keywords[0] === "") {
              resultContent.innerHTML = '<div id="no-result"><i class="fa fa-search fa-5x" /></div>'
            } else if (resultItems.length === 0) {
              resultContent.innerHTML = '<div id="no-result"><i class="fa fa-frown-o fa-5x" /></div>'
            } else {
              resultItems.sort(function (resultLeft, resultRight) {
                if (resultLeft.searchTextCount !== resultRight.searchTextCount) {
                  return resultRight.searchTextCount - resultLeft.searchTextCount;
                } else if (resultLeft.hitCount !== resultRight.hitCount) {
                  return resultRight.hitCount - resultLeft.hitCount;
                } else {
                  return resultRight.id - resultLeft.id;
                }
              });
              var searchResultList = '<ul class=\"search-result-list\">';
              resultItems.forEach(function (result) {
                searchResultList += result.item;
              })
              searchResultList += "</ul>";
              resultContent.innerHTML = searchResultList;
            }
          }

          if ('auto' === 'auto') {
            input.addEventListener('input', inputEventFunction);
          } else {
            $('.search-icon').click(inputEventFunction);
            input.addEventListener('keypress', function (event) {
              if (event.keyCode === 13) {
                inputEventFunction();
              }
            });
          }

          // remove loading animation
          $(".local-search-pop-overlay").remove();
          $('body').css('overflow', '');

          proceedsearch();
        }
      });
    }

    // handle and trigger popup window;
    $('.popup-trigger').click(function(e) {
      e.stopPropagation();
      if (isfetched === false) {
        searchFunc(path, 'local-search-input', 'local-search-result');
      } else {
        proceedsearch();
      };
    });

    $('.popup-btn-close').click(onPopupClose);
    $('.popup').click(function(e){
      e.stopPropagation();
    });
    $(document).on('keyup', function (event) {
      var shouldDismissSearchPopup = event.which === 27 &&
        $('.search-popup').is(':visible');
      if (shouldDismissSearchPopup) {
        onPopupClose();
      }
    });
  </script>





  

  

  

  

  
  

  

  

  

  

</body>
</html>
